//
//  MeController.m
//  Budejie
//
//  Created by 远成物流 on 2017/5/15.
//  Copyright © 2017年 陈梦佳. All rights reserved.
//

#import "MeController.h"
#import "UIBarButtonItem+Item.h"
#import <AFNetworking/AFNetworking.h>
#import <MJExtension/MJExtension.h>
#import "MeCollectionViewModel.h"
#import "MeCollectionViewCell.h"
#import "WebViewController.h"
#import "SettingController.h"

static NSString * const MeCellID = @"MeCell";
static NSInteger const cols = 4;
static NSInteger const space = 1;

#define itemWH (ScreenW-(cols-1)*space)/cols

@interface MeController ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,strong)NSMutableArray *items;

@end

@implementation MeController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIBarButtonItem *settingItem = [UIBarButtonItem itemWithImage:[UIImage imageNamed:@"mine-setting-icon"] highImage:[UIImage imageNamed:@"mine-setting-icon-click"] target:self action:@selector(settingAction)];
    UIBarButtonItem *modelItem = [UIBarButtonItem itemWithImage:[UIImage imageNamed:@"mine-moon-icon"] highImage:[UIImage imageNamed:@"mine-moon-icon-click"] target:self action:@selector(changeModel:)];
    self.navigationItem.rightBarButtonItems = @[settingItem,modelItem];
    self.title = @"我的";
    
    //添加collectionview
    [self setFooterView];
    
    //加载collectionview内容
    [self loadData];
    
    self.tableView.sectionHeaderHeight = 0;
    self.tableView.sectionFooterHeight = 10;;
    
    //tabbar 重复点击通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tabbarRepeatClicked) name:TabBarButtonDidRepeatClickedNotification object:nil];
}

-(void)tabbarRepeatClicked{
    if (self.view.window == nil) {
        return;
    }
    
    NSLog(@"tabbar button repeat clicked");
}

-(void)setFooterView{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(itemWH, itemWH);
    layout.minimumLineSpacing = space;
    layout.minimumInteritemSpacing = space;
    
    UICollectionView *collect = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 0, 300) collectionViewLayout:layout];
    _collectionView = collect;
    collect.backgroundColor = self.tableView.backgroundColor;
    self.tableView.tableFooterView = collect;
    
    collect.dataSource = self;
    collect.delegate = self;
    collect.scrollEnabled = NO;
    
    [collect registerNib:[UINib nibWithNibName:@"MeCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:MeCellID];
}

-(void)loadData{
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    
    NSDictionary *params = @{
                             @"a":@"square",
                             @"c":@"topic"
                             };
    [mgr GET:CommonURL parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSArray *array = responseObject[@"square_list"];
        
        _items = [MeCollectionViewModel mj_objectArrayWithKeyValuesArray:array];
        
        //处理最后一行
        NSInteger exter = _items.count % cols;
        exter = cols - exter;
        for (int i=0; i<exter; i++) {
            MeCollectionViewModel *model = Alloc(MeCollectionViewModel);
            [self.items addObject:model];
        }
        
        //设置collectionview高度
        NSInteger rows = (_items.count-1)/cols+1;
        self.collectionView.height_sd = rows * itemWH;
        
        //设置tableview滚动区域
        self.tableView.tableFooterView = self.collectionView;
        
        [self.collectionView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error.localizedDescription);
    }];
}

#pragma 
-(void)settingAction{
    [self.navigationController pushViewController:[[SettingController alloc] init] animated:YES];
}

-(void)changeModel:(UIButton *)button{
    button.selected = !button.selected;
}

#pragma mark - UICollectionview datasource & delegate
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.items.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    MeCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:MeCellID forIndexPath:indexPath];
    
    cell.item = self.items[indexPath.row];
    
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    MeCollectionViewModel *model = self.items[indexPath.row];
    if (![model.url containsString:@"http"]) {
        return;
    }
    
    WebViewController *web = [[WebViewController alloc] init];
    web.url = model.url;
    [self.navigationController pushViewController:web animated:YES];
}

#pragma mark - UITableView datasource & delegate
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"MeTableViewCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    
    cell.textLabel.text = @"balabala";
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
